package com.example.demo.controller;

import java.io.PrintWriter;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.entity.User;

@Controller
public class ParamController {

	@RequestMapping(value = "/testRequestParam")
	public String testRequestParam(
			@RequestParam(value = "username",required=false) String un,
			@RequestParam(value = "age", required = false, defaultValue = "0") int age,
			Model model) {
		model.addAttribute("name", un);
		model.addAttribute("age", age);
		return "param/test";
	}
	/**
	 * 了解: 映射请求头信息 用法同 @RequestParam
	 * 返回ModelAndView(view,model)
	 * 这是标准写法，直接return viewname as String是简写
	 */
	@RequestMapping("/testRequestHeader")
	public ModelAndView testRequestHeader(
			@RequestHeader(value = "Accept-Language") String al) {
		
		Map<String, Object> model = new ModelMap();
		model.put("lang", al);
		return new ModelAndView("param/head", model);
	}
	
	/**
	 * 了解:
	 * 
	 * @CookieValue: 映射一个 Cookie 值. 属性同 @RequestParam
	 */
	@RequestMapping("/testCookieValue")
	@ResponseBody
	public void testCookieValue(@CookieValue("JSESSIONID") String sessionId,PrintWriter write) {
		write.println("testCookieValue: sessionId: " + sessionId);
	}
	/**
	 * 转向添加用户的表单视图
	 * @return
	 */
	@RequestMapping("/adduser")
	public String addUser() {
		return "param/addUser";
	}
	/**
	 * 接受用户信息并且输出到页面上以JSON的形式
	 * 支持及联注入对象属性
	 * @param user
	 * @return
	 */
	@RequestMapping(value="param/testPojo",method=RequestMethod.POST)
	@ResponseBody
	public Object addUserHandler(@Valid User user) {
		return user;
	}
}
